//
//  ShareClient.m
//  WeiboFon
//
//  Created by kaz on 7/13/08.
//  Copyright naan studio 2008. All rights reserved.
//

#import "ShareClient.h"
#import "ShareKit.h"
#import "ShareError.h"
#import "StringUtil.h"
#import "JSON.h"
#import "OAuth.h"
#import "ASIFormDataRequest.h"
#import "OAToken.h"


@implementation ShareClient

@synthesize hasError;
@synthesize error=_error;
@synthesize shareType=_shareType;
@synthesize responseObject=_responseObject;
@synthesize delegate=_delegate;
@synthesize screenName=_screenName;
@synthesize cachedStatus=_cachedStatus;
@synthesize requestType;

+ (ShareClient*)clientForType:(NSString*)type withConsumer:(OAConsumer *)oAConsumer 
                     andToken:(OAToken*)accessToken;
 {
    if (type==SHARE_SINAWEIBO) {
        return [[[SinaWeiboClient alloc] initWithConsumer:oAConsumer andToken:accessToken] autorelease];
    } else if (type==SHARE_NTESWEIBO) {
        return [[[NTESWeiboClient alloc] initWithConsumer:oAConsumer andToken:accessToken] autorelease];        
    } else if (type==SHARE_QQWEIBO) {
        return [[[QQWeiboClient alloc] initWithConsumer:oAConsumer andToken:accessToken] autorelease];        
    }
    return nil;
}

- (id)initWithConsumer:(OAConsumer *)oAConsumer andToken:(OAToken*)accessToken; {
    if (self=[super init]) {
        _consumer = [oAConsumer retain];
        _accessToken = [accessToken retain];
        _oAuth = [[OAuth alloc] init];
        _oAuth.consumer = _consumer;
    }
    return self;
}


- (void)dealloc {
    [_error release];
    [_consumer release];
    [_accessToken release];
    [_oAuth release];
    [_responseObject release];
    [_cachedStatus release];
    [super dealloc];
}

#pragma mark -
#pragma mark REST API methods
#pragma mark -

-(NSError*)parseRespondError:(NSObject*)data {
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary*)data;
        if (self.shareType==SHARE_QQWEIBO) {
            if ([[dict objectForKey:@"ret"] intValue]!=0) {
                NSString * errorDesc=[NSString stringWithFormat:@"%@",[dict objectForKey:@"msg"]];
                return  [ShareError errorWithCode:kShareErrorLogic 
                                         erorDesc: errorDesc];
            }
        } else {
            if ([dict objectForKey:@"error"]!=nil) {
                NSString * errorDesc=[NSString stringWithFormat:@"%@",[dict objectForKey:@"error"]];
                return  [ShareError errorWithCode:kShareErrorLogic 
                                         erorDesc: errorDesc];
            }
        }
    }
    return nil;
}

-(NSString*)parseScreenName:(NSObject*)data {
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary*)data;
        NSDictionary *user =[dic objectForKey:@"user"];
        if ([user isKindOfClass:[NSDictionary class]]) {
            return [NSString stringWithFormat:@"%@",[user objectForKey:@"screen_name"]];
        }
    }
    return nil;
}

-(void)postFinished {
    if (!self.error) {
        self.error = [self parseRespondError:_responseObject]; 
        self.screenName = [self parseScreenName:_responseObject];
    }
    if (self.delegate&&[self.delegate respondsToSelector:@selector(shareClientFinished:)]) {
        [self.delegate shareClientFinished:self];
    }
}

- (void)post:(NSString*)tweet {
    
    NSString *url =[ShareKitUrl postURL:self.shareType];
    NSDictionary *param =[NSDictionary dictionaryWithObjectsAndKeys:_accessToken.key,@"oauth_token",tweet,@"status",nil];
    NSString *oauth_header = [_oAuth oAuthHeaderForMethod:@"POST" andUrl:url andParams:param andTokenSecret:_accessToken.secret];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    request.delegate = self;
    [request setPostFormat:ASIURLEncodedPostFormat];
    [request setPostValue:tweet forKey:@"status"];
	[request addRequestHeader:@"Authorization" value:oauth_header];
    [request startAsynchronous];
    
    self.requestType = WEIBO_POST_MESSAGE;
}


- (void)upload:(NSData*)jpeg status:(NSString *)status
{
    NSString *url =[ShareKitUrl uploadURL:self.shareType];
    NSDictionary *param =[NSDictionary dictionaryWithObjectsAndKeys:_accessToken.key,@"oauth_token",status,@"status",nil];
    NSString *oauth_header = [_oAuth oAuthHeaderForMethod:@"POST" andUrl:url andParams:param andTokenSecret:_accessToken.secret];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    request.delegate = self;
    [request setPostFormat:ASIMultipartFormDataPostFormat];
    [request setPostValue:status forKey:@"status"];
    [request setData:jpeg withFileName:@"image.jpeg" andContentType:@"image/jpeg" forKey:@"pic"];
	[request addRequestHeader:@"Authorization" value:oauth_header];
    [request startAsynchronous];
    
    self.requestType = WEIBO_UPLOAD;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSString *response = request.responseString;
    self.responseObject =  [response JSONValue];
    self.error = nil;
    [self postFinished];
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    self.error = request.error;
    self.responseObject = nil;
    [self postFinished];
}

@end


@implementation SinaWeiboClient
- (id)initWithConsumer:(OAConsumer *)oAConsumer andToken:(OAToken*)accessToken; {
    if (self=[super initWithConsumer:oAConsumer andToken:accessToken]) {
        _shareType =[SHARE_SINAWEIBO retain];
    }
    return self;
}
@end

@implementation NTESWeiboClient
- (id)initWithConsumer:(OAConsumer *)oAConsumer andToken:(OAToken*)accessToken; {
    if (self=[super initWithConsumer:oAConsumer andToken:accessToken]) {
        _shareType =[SHARE_NTESWEIBO retain];        
    }
    return self;
}

- (void)upload:(NSData*)jpeg status:(NSString *)status {
    self.cachedStatus = status;
    
    NSString *url =[ShareKitUrl uploadURL:self.shareType];
    NSDictionary *param =[NSDictionary dictionaryWithObjectsAndKeys:_accessToken.key,@"oauth_token",nil];
    NSString *oauth_header = [_oAuth oAuthHeaderForMethod:@"POST" andUrl:url andParams:param andTokenSecret:_accessToken.secret];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    request.delegate = self;
    [request setPostFormat:ASIMultipartFormDataPostFormat];
    [request setData:jpeg withFileName:@"image.jpeg" andContentType:@"image/jpeg" forKey:@"pic"];
	[request addRequestHeader:@"Authorization" value:oauth_header];
    [request startAsynchronous];
    
    self.requestType = WEIBO_UPLOAD;
}

-(void)postFinished {
    if (!self.error&&self.requestType==WEIBO_UPLOAD) {
        self.error = [self parseRespondError:_responseObject]; 
        if (!self.error&&[_responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *imageUrl =[(NSDictionary*)_responseObject objectForKey:@"upload_image_url"];
            NSString *status =[NSString stringWithFormat:@"%@%@",self.cachedStatus,imageUrl];
            [self post:status];
            return;
        }
    }
    [super postFinished];
}

@end


@implementation QQWeiboClient
- (id)initWithConsumer:(OAConsumer *)oAConsumer andToken:(OAToken*)accessToken; {
    if (self=[super initWithConsumer:oAConsumer andToken:accessToken]) {
        _shareType =[SHARE_QQWEIBO retain];        
    }
    return self;
}

- (void)post:(NSString*)tweet {
    
    NSString *url =[ShareKitUrl postURL:self.shareType];
    NSMutableDictionary *param =[NSMutableDictionary dictionaryWithObjectsAndKeys:_accessToken.key,@"oauth_token",tweet,@"content",nil];      
    NSString *signature = [_oAuth oAuthSignatureForMethod:@"POST" andUrl:url andParams:param andTokenSecret:_accessToken.secret];     
    [param addEntriesFromDictionary:_oAuth.basicOAuthParam];
    
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    [request setPostFormat:ASIURLEncodedPostFormat];
    for (NSString *key in [[param allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
        [request setPostValue:[param objectForKey:key] forKey:key];
    }
    [request setPostValue:signature forKey:@"oauth_signature"];
    request.delegate = self;
	[request startAsynchronous];
    
    self.requestType = WEIBO_POST_MESSAGE;
}

- (void)upload:(NSData*)jpeg status:(NSString *)status
{
    NSString *url =[ShareKitUrl uploadURL:self.shareType];
    
    NSMutableDictionary *param =[NSMutableDictionary dictionaryWithObjectsAndKeys:_accessToken.key,@"oauth_token",status,@"content",nil];
    NSString *signature = [_oAuth oAuthSignatureForMethod:@"POST" andUrl:url andParams:param andTokenSecret:_accessToken.secret];     
    [param addEntriesFromDictionary:_oAuth.basicOAuthParam];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    request.delegate = self;
    [request setPostFormat:ASIMultipartFormDataPostFormat];
    for (NSString *key in [[param allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
        [request setPostValue:[param objectForKey:key] forKey:key];
    }
    [request setPostValue:signature forKey:@"oauth_signature"];
    [request setData:jpeg withFileName:@"image.jpeg" andContentType:@"image/jpeg" forKey:@"pic"];
    [request startAsynchronous];
    
    self.requestType = WEIBO_UPLOAD;
}
@end

